import React, {Component} from 'react';
import {
  SafeAreaView,
  FlatList,
  StyleSheet,
  View,
  Text,
  StatusBar,
  ScrollView,
  Dimensions,
  KeyboardAvoidingView,
  Modal,
  Image,
  TouchableOpacity,
} from 'react-native';
import ImageViewer from 'react-native-image-zoom-viewer';
import {Colors} from 'react-native/Libraries/NewAppScreen';

import {ListItem, Button, Input} from 'react-native-elements';
import {Actions} from 'react-native-router-flux';
import ListEditItem from '../views/ListEditItem';
import Api from '../Api';
import DateUtils from '../utils/DateUtils';
import Dialog from '../components/Dialog';
import {showToast} from '../utils';

const windowWidth = Dimensions.get('window').width;
const windowHeight = Dimensions.get('window').height;

export default class WorksheetDetailScreen extends Component {
  constructor(props) {
    super(props);
    this.state = {
      sheetDetail: {},
      content: '',
      logs: [], // 操作日志
      showImageViewer: false,
      previewImages: [],
      previewIndex: 0,
    };
  }

  componentDidMount() {
    const {item} = this.props.navigation.state.params;
    this.setState({sheetDetail: item});
    this.getWorksheetLog();
    if (item.serviceLevel) {
      Api.dictDetail(item.serviceLevel).then(data => {
        this.setState({
          serviceLevel: data.label,
        });
      });
    }
    //TODO 设备名称名称
    if (item.taccident) {
      Api.getDeviceNames(item.taccident.faultDevice).then(data => {
        this.setState({
          deviceNames: data.value,
        });
      });
    }
  }

  componentWillUnmount() {
    const {item} = this.props.navigation.state.params;
    const {sheetDetail} = this.state;
    // 状态变更之后，返回刷新页面
    if (item.status !== sheetDetail.status) {
      setTimeout(() => {
        Actions.refresh({
          updateTime: new Date(),
        });
      }, 100);
    }
  }

  getWorksheetLog() {
    const {item} = this.props.navigation.state.params;
    Api.worksheetLog(item.orderCode).then(data => {
      this.setState({
        logs: data.content,
      });
    });
  }

  // 检查工单是否填写完毕
  checkContent() {
    if (!this.state.content) {
      showToast('工单处理内容不能为空');
      return false;
    }
    return true;
  }
  // 工作状态变更
  updateWorkStatus(status) {
    const {id} = this.state.sheetDetail;
    Api.workorderprocess(id, this.state.content, status)
      .then(res => {
        if (res.status === 200) {
          showToast('工单处理成功');
          this.setState({
            sheetDetail: {
              ...this.state.sheetDetail,
              status,
            },
          });
          this.getWorksheetLog();
        } else {
          showToast(res.body.message || '处理失败');
        }
      })
      .catch(err => {
        console.log(err);
        showToast('处理失败');
      });
  }

  refuseWork(status) {
    this.dialog.show({
      content: '确认拒单吗？',
      handleConfirm: () => {
        this.updateWorkStatus(status);
      },
    });
  }

  receiveWork(status) {
    this.dialog.show({
      content: '确认接单吗？',
      handleConfirm: () => {
        this.updateWorkStatus(status);
      },
    });
  }

  doingWork(status) {
    this.updateWorkStatus(status);
  }

  returnWork(status) {
    this.dialog.show({
      input: true,
      placeholder: '请输入退回原因',
      handleConfirm: ({content}) => {
        this.setState(
          {
            content,
          },
          () => {
            this.updateWorkStatus(status);
          },
        );
      },
    });
  }

  backWork(status) {
    this.dialog.show({
      input: true,
      placeholder: '请输入处理意见',
      handleConfirm: ({content}) => {
        // 是否退回
        this.setState(
          {
            content,
          },
          () => {
            this.updateWorkStatus(status);
          },
        );
      },
    });
  }

  endWork(status) {
    this.dialog.show({
      content: '确认结单吗？',
      handleConfirm: () => {
        this.updateWorkStatus(status);
      },
    });
  }

  // 渲染故障工单明细
  renderToubleWork() {
    const {sheetDetail, deviceNames} = this.state;
    const photos =
      sheetDetail.taccident && sheetDetail.taccident.faultPicture
        ? sheetDetail.taccident.faultPicture.split(',')
        : [];
    const remotePhotos = photos.map(item => Api.photo(item));
    return (
      <>
        <ListItem bottomDivider>
          <ListItem.Content>
            <ListItem.Title style={styles.title}>客户名称</ListItem.Title>
          </ListItem.Content>
          <ListItem.Content right>
            <ListItem.Title right style={styles.rightTitle}>
              {sheetDetail.taccident && sheetDetail.taccident.customerName}
            </ListItem.Title>
          </ListItem.Content>
        </ListItem>
        <ListItem bottomDivider>
          <ListItem.Content>
            <ListItem.Title style={styles.title}>报修设备</ListItem.Title>
          </ListItem.Content>
          <ListItem.Content right>
            <ListItem.Title right style={styles.rightTitle}>
              {deviceNames}
            </ListItem.Title>
          </ListItem.Content>
        </ListItem>
        <ListItem bottomDivider>
          <ListItem.Content>
            <ListItem.Title style={styles.title}>报修地区</ListItem.Title>
          </ListItem.Content>
          <ListItem.Content right>
            <ListItem.Title right style={styles.rightTitle}>
              {sheetDetail.taccident && sheetDetail.taccident.country &&  `${sheetDetail.taccident.country}/${sheetDetail.taccident.province}/${sheetDetail.taccident.city}/${sheetDetail.taccident.county}`}{' '}
            </ListItem.Title>
          </ListItem.Content>
        </ListItem>
        <ListItem bottomDivider>
          <ListItem.Content>
            <ListItem.Title style={styles.title}>报修地址</ListItem.Title>
          </ListItem.Content>
          <ListItem.Content right>
            <ListItem.Title right style={styles.rightTitle}>
              {sheetDetail.taccident && sheetDetail.taccident.address}{' '}
            </ListItem.Title>
          </ListItem.Content>
        </ListItem>
        <ListItem bottomDivider>
          <ListItem.Content>
            <ListItem.Title style={styles.title}>故障描述</ListItem.Title>
          </ListItem.Content>
          <ListItem.Content right>
            <ListItem.Title right style={styles.rightTitle}>
              {sheetDetail.taccident && sheetDetail.taccident.faultDesc}
            </ListItem.Title>
          </ListItem.Content>
        </ListItem>
        <ListItem bottomDivider>
          <ListItem.Content>
            <ListItem.Title style={styles.title}>报修时间</ListItem.Title>
          </ListItem.Content>
          <ListItem.Content right>
            <ListItem.Title right style={styles.rightTitle}>
              {sheetDetail.taccident && sheetDetail.taccident.reportTime}
            </ListItem.Title>
          </ListItem.Content>
        </ListItem>
        <ListItem bottomDivider>
          <ListItem.Content>
            <ListItem.Title style={styles.title}>要求到场时间</ListItem.Title>
          </ListItem.Content>
          <ListItem.Content right>
            <ListItem.Title right style={styles.rightTitle}>
              {sheetDetail.taccident && sheetDetail.taccident.reqiureTime}
            </ListItem.Title>
          </ListItem.Content>
        </ListItem>
        <ListItem bottomDivider>
          <ListItem.Content>
            <ListItem.Title style={styles.title}>联系人</ListItem.Title>
          </ListItem.Content>
          <ListItem.Content right>
            <ListItem.Title right style={styles.rightTitle}>
              {sheetDetail.taccident && sheetDetail.taccident.linker}{' '}
            </ListItem.Title>
          </ListItem.Content>
        </ListItem>
        <ListItem bottomDivider>
          <ListItem.Content>
            <ListItem.Title style={styles.title}>联系电话</ListItem.Title>
          </ListItem.Content>
          <ListItem.Content right>
            <ListItem.Title right style={styles.rightTitle}>
              {sheetDetail.taccident && sheetDetail.taccident.cellphone}
            </ListItem.Title>
          </ListItem.Content>
        </ListItem>
        <ListItem bottomDivider>
          <ListItem.Content>
            <ListItem.Title style={styles.title}>备注</ListItem.Title>
          </ListItem.Content>
          <ListItem.Content right>
            <ListItem.Title right style={styles.rightTitle}>
              {sheetDetail.taccident && sheetDetail.taccident.notes}{' '}
            </ListItem.Title>
          </ListItem.Content>
        </ListItem>
        <ListItem bottomDivider>
          <ListItem.Content>
            <ListItem.Title style={styles.title}>故障图片</ListItem.Title>
          </ListItem.Content>
          <ListItem.Content right style={{flex: 1}}>
            <View style={styles.photos}>
              {remotePhotos.map((l, i) => {
                return (
                  <TouchableOpacity
                    key={i}
                    onPress={() => {
                      this.setState({
                        previewImages: remotePhotos.map(item => ({
                          url: item.uri,
                          width: windowWidth,
                          height: windowHeight,
                          props: {
                            source: {
                              headers: item.headers,
                            },
                            style: {
                              resizeMode: 'contain',
                            },
                          },
                        })),
                        previewIndex: i,
                        showImageViewer: true,
                      });
                    }}>
                    <Image style={styles.photosThumb} source={l} />
                  </TouchableOpacity>
                );
              })}
            </View>
          </ListItem.Content>
        </ListItem>
      </>
    );
  }

  // 渲染任务工单明细
  renderTaskWork() {
    const {sheetDetail, deviceNames} = this.state;
    return (
      <>
        <ListItem bottomDivider>
          <ListItem.Content>
            <ListItem.Title style={styles.title}>任务名称</ListItem.Title>
          </ListItem.Content>
          <ListItem.Content right>
            <ListItem.Title right style={styles.rightTitle}>
              {sheetDetail.task && sheetDetail.task.taskTitle}
            </ListItem.Title>
          </ListItem.Content>
        </ListItem>
        <ListItem bottomDivider>
          <ListItem.Content>
            <ListItem.Title style={styles.title}>任务内容</ListItem.Title>
          </ListItem.Content>
          <ListItem.Content right>
            <ListItem.Title right style={styles.rightTitle}>
              {sheetDetail.task && sheetDetail.task.taskContent}
            </ListItem.Title>
          </ListItem.Content>
        </ListItem>
        <ListItem bottomDivider>
          <ListItem.Content>
            <ListItem.Title style={styles.title}>任务地区</ListItem.Title>
          </ListItem.Content>
          <ListItem.Content right>
            <ListItem.Title right style={styles.rightTitle}>
              {sheetDetail.task && sheetDetail.task.country && `${sheetDetail.task.country}/${sheetDetail.task.province}/${sheetDetail.task.city}/${sheetDetail.task.county}`}{' '}
            </ListItem.Title>
          </ListItem.Content>
        </ListItem>
        <ListItem bottomDivider>
          <ListItem.Content>
            <ListItem.Title style={styles.title}>任务地址</ListItem.Title>
          </ListItem.Content>
          <ListItem.Content right>
            <ListItem.Title right style={styles.rightTitle}>
              {sheetDetail.task && sheetDetail.task.taskAddr}
            </ListItem.Title>
          </ListItem.Content>
        </ListItem>
        <ListItem bottomDivider>
          <ListItem.Content>
            <ListItem.Title style={styles.title}>发起时间</ListItem.Title>
          </ListItem.Content>
          <ListItem.Content right>
            <ListItem.Title right style={styles.rightTitle}>
              {sheetDetail.task && sheetDetail.task.startTime}
            </ListItem.Title>
          </ListItem.Content>
        </ListItem>
        <ListItem bottomDivider>
          <ListItem.Content>
            <ListItem.Title style={styles.title}>联系人</ListItem.Title>
          </ListItem.Content>
          <ListItem.Content right>
            <ListItem.Title right style={styles.rightTitle}>
              {sheetDetail.task && sheetDetail.task.linker}
            </ListItem.Title>
          </ListItem.Content>
        </ListItem>
        <ListItem bottomDivider>
          <ListItem.Content>
            <ListItem.Title style={styles.title}>联系电话</ListItem.Title>
          </ListItem.Content>
          <ListItem.Content right>
            <ListItem.Title right style={styles.rightTitle}>
              {sheetDetail.task && sheetDetail.task.cellphone}
            </ListItem.Title>
          </ListItem.Content>
        </ListItem>
        <ListItem bottomDivider>
          <ListItem.Content>
            <ListItem.Title style={styles.title}>要求到场时间</ListItem.Title>
          </ListItem.Content>
          <ListItem.Content right>
            <ListItem.Title right style={styles.rightTitle}>
              {sheetDetail.task && sheetDetail.task.arriveTime}
            </ListItem.Title>
          </ListItem.Content>
        </ListItem>
        <ListItem bottomDivider>
          <ListItem.Content>
            <ListItem.Title style={styles.title}>要求完成时间</ListItem.Title>
          </ListItem.Content>
          <ListItem.Content right>
            <ListItem.Title right style={styles.rightTitle}>
              {sheetDetail.task && sheetDetail.task.finishTime}
            </ListItem.Title>
          </ListItem.Content>
        </ListItem>
        <ListItem bottomDivider>
          <ListItem.Content>
            <ListItem.Title style={styles.title}>备注</ListItem.Title>
          </ListItem.Content>
          <ListItem.Content right>
            <ListItem.Title right style={styles.rightTitle}>
              {sheetDetail.task && sheetDetail.task.notes}
            </ListItem.Title>
          </ListItem.Content>
        </ListItem>
      </>
    );
  }

  returnFunction(status) {
    switch (Number(status)) {
      case 201:
        // 服务商拒单
        this.refuseWork(201);
        break;
      case 300:
        // 服务商接单
        this.receiveWork(300);
        break;
      case 400:
        // 到场(维修中)
        this.doingWork(400);
        break;
      case 401:
        // 退回
        this.returnWork(401);
        break;
      case 500:
        // 回单：表示输入施工内容建议后，后续还需要再来
        this.backWork(500);
        break;
      case 600:
        // 结单
        this.endWork(600);
      case 700:
        // 结束
        break;
    }
  }
  // 渲染底部按钮
  renderBottomBtn = () => {
    const {sheetDetail} = this.state;
    const btnStatus = Api.nextStatus(sheetDetail.status);
    return !!btnStatus.length ? (
      <View style={styles.submitBot}>
        {btnStatus.map((status, idx) => (
          <Button
            title={Api.getStatus(status)}
            key={idx}
            buttonStyle={{
              minWidth: btnStatus.length > 2 ? 100 : 150,
              height: 50,
              backgroundColor: status % 100 ? '#ec1561' : '#4388d6',
            }}
            onPress={() => {
              this.returnFunction(status);
            }}
          />
        ))}
      </View>
    ) : null;
  };

  render() {
    const {
      sheetDetail,
      serviceLevel,
      logs,
      deviceNames,
      showImageViewer,
      previewImages,
      previewIndex,
    } = this.state;
    return (
      <SafeAreaView style={{flex: 1}}>
        <StatusBar barStyle="light-content" backgroundColor="#5096fc" />
        <KeyboardAvoidingView
          behavior={Platform.OS == 'ios' ? 'padding' : 'height'}
          style={{flex: 1}}>
          <ScrollView style={{flex: 1}} keyboardDismissMode="on-drag">
            {sheetDetail ? (
              <View>
                <ListItem bottomDivider>
                  <ListItem.Content>
                    <ListItem.Title style={styles.title}>
                      工单编号
                    </ListItem.Title>
                  </ListItem.Content>
                  <ListItem.Content right>
                    <ListItem.Title right style={styles.rightTitle}>
                      {sheetDetail.orderCode}
                    </ListItem.Title>
                  </ListItem.Content>
                </ListItem>
                <ListItem bottomDivider>
                  <ListItem.Content>
                    <ListItem.Title style={styles.title}>
                      工单状态
                    </ListItem.Title>
                  </ListItem.Content>
                  <ListItem.Content right>
                    <ListItem.Title right style={styles.rightTitle}>
                      {Api.getStatus(sheetDetail.status)}
                    </ListItem.Title>
                  </ListItem.Content>
                </ListItem>
                <ListItem bottomDivider>
                  <ListItem.Content>
                    <ListItem.Title style={styles.title}>
                      服务等级
                    </ListItem.Title>
                  </ListItem.Content>
                  <ListItem.Content right>
                    <ListItem.Title right style={styles.rightTitle}>
                      {serviceLevel}
                    </ListItem.Title>
                  </ListItem.Content>
                </ListItem>
                {sheetDetail.orderSource === 1
                  ? this.renderToubleWork()
                  : sheetDetail.orderSource === 2
                  ? this.renderTaskWork()
                  : null}
                <Text style={styles.sectionTitle}>操作日志</Text>
                {logs.map((item, idx) => (
                  <ListItem bottomDivider key={idx}>
                    <ListItem.Content>
                      <ListItem.Title>{item.content}</ListItem.Title>
                      <ListItem.Subtitle>
                        {DateUtils.formatDate(
                          'y-m-d h:i:s',
                          new Date(item.createTime),
                        )}
                      </ListItem.Subtitle>
                    </ListItem.Content>
                    <ListItem.Content right>
                      <ListItem.Title right>{item.operator}</ListItem.Title>
                      <ListItem.Subtitle right>
                        {Api.getStatus(item.orderStatus)}
                      </ListItem.Subtitle>
                    </ListItem.Content>
                  </ListItem>
                ))}
                <Modal visible={showImageViewer} transparent={true}>
                  <ImageViewer
                    imageUrls={previewImages}
                    index={previewIndex}
                    onClick={() => {
                      this.setState({
                        showImageViewer: false,
                        previewImages: [],
                      });
                    }}
                  />
                </Modal>
              </View>
            ) : null}
            <Dialog ref={e => (this.dialog = e)} />
          </ScrollView>
          {this.renderBottomBtn()}
        </KeyboardAvoidingView>
      </SafeAreaView>
    );
  }
}

const styles = StyleSheet.create({
  rightTitle: {
    color: Colors.black,
    width: windowWidth - 160,
  },
  title: {
    textAlign: 'right',
    width: 110,
  },
  submitBot: {
    paddingHorizontal: 20,
    paddingVertical: 8,
    flexDirection: 'row',
    flexWrap: 'nowrap',
    justifyContent: 'space-around',
  },
  sectionTitle: {
    paddingLeft: 15,
    paddingTop: 10,
    paddingBottom: 10,
    fontWeight: 'bold',
    fontSize: 18,
  },
  photos: {
    flexDirection: 'row',
    flexWrap: 'wrap',
    justifyContent: 'flex-start',
    alignItems: 'center',
    width: windowWidth - 160,
  },
  photosThumb: {
    width: 100,
    height: 100,
    margin: 10,
  },
});
